package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.HospitalGoodsBaseData;
import cn.com.ejiakanghu.dto.HospitalOrderListBackData;
import cn.com.ejiakanghu.dto.HospitalOrderListVo;
import cn.com.ejiakanghu.vo.UpdateDeviceStatusVo;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.app.AppHospitalMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.dto.HospitalEquListDto;
import org.linlinjava.litemall.db.dto.HospitalOrderListDto;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wj
 * @date 2022/1/21 15:18
 */
@Service
@Transactional
public class HospitalManage {

    @Resource
    private AgedmallHospitalWizardOrderRecordMapper agedmallHospitalWizardOrderRecordMapper;

    @Resource
    private AgedmallHospitalWizardOrderMapper agedmallHospitalWizardOrderMapper;

    @Resource
    private AppHospitalMapper appHospitalMapper;

    @Resource
    private LitemallUserMapper litemallUserMapper;

    @Resource
    private AgedmallHospitalSiteRentalMapper agedmallHospitalSiteRentalMapper;

    @Resource
    private AgedmallHospitalSendSelfLocationEquMapper agedmallHospitalSendSelfLocationEquMapper;

    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;

    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;


    /**
     * DB -> WEB
     * 设备状态转换
     */
    public Integer transformStateDbToWeb(Integer dbState){
        switch (dbState){
            case 0:
            case 1:
                return 0;
            case 2:
                return 3;
            case 3:
                return 2;
            case 4:
                return 1;
            default:
                return 0;
        }
    }


    public BaseResult deviceList(Integer userId){
        Map<String,Object> map=new HashMap<>();
        Integer idleCount=0;
        Integer subCount=0;
        LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(userId);
        List<HospitalEquListDto> hospitalEquListByUserId = appHospitalMapper.getHospitalEquListByUserPhone(litemallUser.getMobile());
        for (int i = 0; i < hospitalEquListByUserId.size(); i++) {
            Integer webState=transformStateDbToWeb(hospitalEquListByUserId.get(i).getDeviceStatus());
            hospitalEquListByUserId.get(i).setDeviceStatus(webState);
            switch (webState){
                case 0:
                    idleCount++;
                case 1:
                    subCount++;
                default:
                    continue;
            }
        }
        map.put("totalCount",hospitalEquListByUserId.size());
        map.put("idleCount",idleCount);
        map.put("subCount",subCount);
        map.put("deviceList",hospitalEquListByUserId);
        return RespUtil.success(map);
    }


    public BaseResult orderList(Integer userId,HospitalOrderListVo hospitalOrderListVo){
        Map<String,Object> map=new HashMap<>();
        LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(userId);
        Page page = PageHelper.startPage(hospitalOrderListVo.getPage(), hospitalOrderListVo.getPageSize());
        List<HospitalOrderListDto> hospitalOrderListByUserPhone = appHospitalMapper.getHospitalOrderListByUserPhone(litemallUser.getMobile());
        List<HospitalOrderListBackData> hospitalOrderListBackDataList =new ArrayList<>();
        for (int i = 0; i < hospitalOrderListByUserPhone.size(); i++) {
            HospitalGoodsBaseData hospitalGoodsBaseData=new HospitalGoodsBaseData(hospitalOrderListByUserPhone.get(i));
            HospitalOrderListBackData hospitalOrderListBackData=new HospitalOrderListBackData(hospitalOrderListByUserPhone.get(i),hospitalGoodsBaseData);
            hospitalOrderListBackDataList.add(hospitalOrderListBackData);
        }
        map.put("nowPage",hospitalOrderListVo.getPage());
        map.put("totalPage",page.getPages());
        map.put("totalRows",page.getTotal());
        map.put("rows",hospitalOrderListBackDataList);

        return RespUtil.success(map);
    }

    public BaseResult updateDeviceStatus(Integer userId,UpdateDeviceStatusVo updateDeviceStatusVo){
        AgedmallHospitalSendSelfLocationEqu locationEqu=agedmallHospitalSendSelfLocationEquMapper.selectByPrimaryKey(updateDeviceStatusVo.getDeviceId().longValue());
        //改变后状态
        Integer changeState=0;
        //rfid状态
        Integer goodsEquState=0;
        //当前导医台订单状态
        Integer nowWizardState=0;
        switch (updateDeviceStatusVo.getAction()){
                //确认取走
            case "confirm_pickup":
                 changeState=1;
                 goodsEquState=3;
                nowWizardState=0;
                changeWizardOrder(userId.longValue(),locationEqu,nowWizardState,changeState,goodsEquState);
                break;

                //确认归还
            case "confirm_retrurn":
                changeState=2;
                goodsEquState=0;
                nowWizardState=1;
                //首先判断归还的是不是围老下单的
                AgedmallHospitalWizardOrderExample wizardOrderExample=new AgedmallHospitalWizardOrderExample();
                wizardOrderExample.createCriteria().andHospitalSelfLocationIdEqualTo(locationEqu.getHospitalSelfLocationId()).
                        andLockRfidEqualTo(locationEqu.getEquId().intValue()).andStateEqualTo(nowWizardState);
                AgedmallHospitalWizardOrder wizardOrder=agedmallHospitalWizardOrderMapper.selectOneByExample(wizardOrderExample);
                if(ObjectUtil.isNotNull(wizardOrder)){
                    changeWizardOrder(userId.longValue(),locationEqu,nowWizardState,changeState,goodsEquState);
                }
                else{
                    insertSiteRental(userId,locationEqu.getEquId().intValue(),changeState);
                    changeHospitalRfidState(locationEqu.getEquId(),goodsEquState);
                }
                break;

                //设置维修
            case "confirm_repair":
                goodsEquState=2;
                changeHospitalRfidState(locationEqu.getEquId(),goodsEquState);

                break;

                //完成维修
            case "finish_repair":
                goodsEquState=0;
                changeHospitalRfidState(locationEqu.getEquId(),goodsEquState);
                break;

                //现场租借
            case "scene_lease":
                changeState=1;
                goodsEquState=3;
                changeHospitalRfidState(locationEqu.getEquId(),goodsEquState);
                insertSiteRental(userId,locationEqu.getEquId().intValue(),changeState);
                break;
            default:
                break;
        }

        return RespUtil.success();
    }




    /**
     * 改变订单状态
     * @param userId
     * @param locationEqu
     * @param changeState
     * @param goodsEquState
     */
    public void changeWizardOrder(Long userId,AgedmallHospitalSendSelfLocationEqu locationEqu,Integer nowWizardOrderState,Integer changeState,Integer goodsEquState){
        AgedmallHospitalWizardOrderExample wizardOrderExample=new AgedmallHospitalWizardOrderExample();
        wizardOrderExample.createCriteria().andHospitalSelfLocationIdEqualTo(locationEqu.getHospitalSelfLocationId()).
                andLockRfidEqualTo(locationEqu.getEquId().intValue()).andStateEqualTo(nowWizardOrderState);

        AgedmallHospitalWizardOrder wizardOrder=agedmallHospitalWizardOrderMapper.selectOneByExample(wizardOrderExample);
        wizardOrder.setState(changeState);

        LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(wizardOrder.getOrderItemId());
        if(changeState==1){
            orderItem.setOrderStatus(OrderUtil.STATUS_LEASE_CONFIRM);
        }
        else if(changeState==2){
            orderItem.setOrderStatus(OrderUtil.STATUS_RETURN_SUCCESS);
        }


        changeHospitalRfidState(wizardOrder.getLockRfid().longValue(),goodsEquState);

        agedmallHospitalWizardOrderMapper.updateByPrimaryKeySelective(wizardOrder);
        litemallOrderItemMapper.updateByPrimaryKeySelective(orderItem);
        //增加导医台订单记录表
        AgedmallHospitalWizardOrderRecord wizardOrderRecord=new AgedmallHospitalWizardOrderRecord();
        wizardOrderRecord.setHospitalWizardOrderId(wizardOrder.getId());
        wizardOrderRecord.setChangeState(changeState);
        //0代表系统操作
        wizardOrderRecord.setOperatorUser(userId);
        wizardOrderRecord.setOperatorTime(LocalDateTime.now());
        agedmallHospitalWizardOrderRecordMapper.insertSelective(wizardOrderRecord);
    }

    /**
     * 修改医院库存的rfid状态
     */
    public void changeHospitalRfidState(Long rfid,Integer state){
        AgedmallGoodsEquExample goodsEquExample=new AgedmallGoodsEquExample();
        goodsEquExample.createCriteria().andDeletedEqualTo((byte)0).andEquIdEqualTo(rfid).andTypeEqualTo(2);
        AgedmallGoodsEqu goodsEqu=new AgedmallGoodsEqu();
        goodsEqu.setState(state);
        agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu,goodsEquExample);
    }

    /**
     *  增加现场租赁数据
     */
    public void insertSiteRental(Integer userId,Integer rfid,Integer changeState){

        AgedmallHospitalSiteRental siteRental=new AgedmallHospitalSiteRental();
        siteRental.setAddTime(LocalDateTime.now());
        siteRental.setEquId(rfid);
        siteRental.setOperatorUser(userId);
        siteRental.setChangeState(changeState);
        agedmallHospitalSiteRentalMapper.insertSelective(siteRental);
    }

}
